<!DOCTYPE html>
<html lang="en">
<title>订单管理--体测订单</title>
<#import "/layout/layout.html" as body/>
<@body.page>

<style>
    a {
        color: #666;
    }
    .tcdPageCode {
        padding: 15px 20px;
        text-align: left;
        color: #ccc;
    }
    .tcdPageCode a {
        display: inline-block;
        color: #428bca;
        height: 25px;
        line-height: 25px;
        padding: 0 10px;
        border: 1px solid #ddd;
        margin: 0 2px;
        border-radius: 4px;
        vertical-align: middle;
    }
    .tcdPageCode a:hover {
        text-decoration: none;
        border: 1px solid #428bca;
    }
    .tcdPageCode span.current {
        display: inline-block;
        height: 25px;
        line-height: 25px;
        padding: 0 10px;
        margin: 0 2px;
        color: #fff;
        background-color: #428bca;
        border: 1px solid #428bca;
        border-radius: 4px;
        vertical-align: middle;
    }
    .tcdPageCode span.disabled {
        display: inline-block;
        height: 25px;
        line-height: 25px;
        padding: 0 10px;
        margin: 0 2px;
        color: #bfbfbf;
        background: #f2f2f2;
        border: 1px solid #bfbfbf;
        border-radius: 4px;
        vertical-align: middle;
    }
    .chosen-container {
        min-width: 160px !important;
    }
    .modal-loading { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 10000; background: rgba(0, 0, 0, .5) url("${baseUrl}img/loading.gif") no-repeat center; }
</style>
<div class="modal-loading"></div>
<div class="wrapper wrapper-content animated fadeIn">
    <div class="row">
        <div class="col-lg-12 margin-top">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5 class="pull-left">私教体测订单</h5>
                </div>
                <div class="ibox-content">
                    <ul class="nav navbar-nav status-nav" id="ul_id">
                        <li class="active"><a href="#">已支付</a></li>
                        <li><a href="#" >未支付</a></li>
                        <li><a href="#" >已结束</a></li>
                        <li><a href="#" >已取消</a></li>
                        <li><a href="#" >已退款</a></li>
                    </ul>
                    <div class="wrapper wrapper-content animated fadeInRight">
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="ibox float-e-margins">
                                    <div class="ibox-content">
                                        <form class="form-inline" role="form" action="" role="form" id="form" method="post" accept-charset="UTF-8">
                                            <div class="form-group margin-left">
                                                <label for="tradeId">订单号：</label>
                                                <input class="form-control" id="orderNumber" name="orderNumber" type="text" placeholder="订单号" value=""/>
                                            </div>
                                            <div class="form-group margin-left">
                                                <label>教练：</label>
                                            </div>
                                            <div class="form-group margin-left" style="">
                                                <select data-placeholder="请输入教练" class="chosen-select coach_list" style="width:80%;" tabindex="2" id="coach_list">
                                                    <option value="0">全部</option>
                                                </select>
                                            </div>
                                            <div class="form-group margin-left">
                                                <label for="mobile">用户手机：</label>
                                                <input class="form-control" id="mobile" type="text" style="width:150px" name = "mobile" placeholder="请输入用户手机号"/>
                                            </div>
                                            <div class="form-group margin-left">
                                                <label for="userId">用户ID：</label>
                                                <input class="form-control" id="userId" name="userId" type="text" style="width:150px" placeholder="请输入用户ID"/>
                                            </div>
                                            <div class="form-group margin-left">
                                                <label for="nickName">用户昵称：</label>
                                                <input class="form-control" id="nickName" name="nickName" type="text" style="width:150px" placeholder="请输入用户昵称"/>
                                            </div>
                                            <div class="form-group margin-left">
                                                <label>门店：</label>
                                            </div>
                                            <div class="form-group margin-left">
                                                <select data-placeholder="请输入门店" class="chosen-select store_list" style="width:80%;" tabindex="2" id="store_list">
                                                    <option value="0">全部</option>
                                                </select>
                                            </div>
                                            <button type="button" class="btn btn-outline btn-primary" style="margin-top: 5px" id="but_submit">确认</button>
                                        	<input type="hidden" id="pageNum" name = "pageNum" >
                                        	<input type="hidden" id="orderStatus" name = "orderStatus" value="1">
                                        </form>
                                        <hr>
                                        <div class="table-responsive">
                                            <!-- dataTables-example -->
                                            <table class="table table-hover table-center dataTables-example">
                                                <thead>
                                                <tr>
                                                    <th>序号</th>
                                                    <th>交易编号</th>
                                                    <th id="tk_th">下订单时间</th>
                                                    <th>订单号</th>
                                                    <th>教练</th>
                                                    <th>用户</th>
                                                    <th>身份</th>
                                                    <th>费用</th>
                                                    <th>优惠券</th>
                                                    <th>购买人数</th>
                                                    <th>实付</th>
                                                    <th>操作</th>
                                                </tr>
                                                </thead>
                                                <!-- 页面加载的数据  -->
                                                <tbody id="td1">
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
									<div class="ibox-footer overflow" id="tk_dibu">
										<h4 class="pull-left margin-left" id="orderCount" style="color: #2fb146">订单合计：0笔</h4>
										<h4 class="pull-left margin-left" id="orderCost" style="color: #2fb146">费用合计：¥0</h4>
										<h4 class="pull-left" id="orderActualAmount" style="color: #2fb146">实付合计：¥0</h4>
										<div class="pull-right copot-page" id="tk_page_list"></div>
									</div>
								</div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<!-- 模态框 start -->
<div class="modal fade" id="coach_myModal" tabindex="-1" role="dialog" >
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel" >是否确认转单</h4>
      </div>
      <div class="modal-body">
				<div class="row">
					<div class="col-lg-12">
						<div class="ibox float-e-margins">
							<form class="form-inline" role="form" action="" role="form2" id="form2" method="post" accept-charset="UTF-8">
								<input type="hidden" name="coachOrderId" id="coachOrderId">
								<div class="form-group margin-left">
									<label>转给教练：</label>
								</div>
								<select data-placeholder="请输入教练" class="chosen-select coach_list"
									style="width: 80%;" tabindex="2" id="coach_list_order">
								</select>
							</form>
						</div>
					</div>
				</div>
	  </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="coachTransferenceOrder">确定</button>
      </div>
    </div>
  </div>
</div>
<!-- 模态框 start -->

<!-- mode start -->
<input type="hidden" id="click_order_type" value="团体课程">
<input type="hidden" id="order_type_child" value="1">
<input type="hidden" id="baseUrl" value="${baseUrl}">
<!-- mode end  -->
<link href="${baseUrl}css/plugins/clockpicker/clockpicker.css" rel="stylesheet">
<script src="${baseUrl}js/plugins/clockpicker/clockpicker.js"></script>
<!-- <script type="text/javascript" src="${baseUrl}js/order/orderInfo.js"></script> -->
<script>

    $(document).ready(function () {
    	Date.prototype.pattern = function (fmt) {

            var o = {
                "M+": this.getMonth() + 1, // 月份
                "d+": this.getDate(), // 日
                "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
                "H+": this.getHours(), // 小时
                "m+": this.getMinutes(), // 分
                "s+": this.getSeconds(), // 秒
                "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
                "S": this.getMilliseconds() // 毫秒
            };
            var week = {
                "0": "/u65e5",
                "1": "/u4e00",
                "2": "/u4e8c",
                "3": "/u4e09",
                "4": "/u56db",
                "5": "/u4e94",
                "6": "/u516d"
            };
            if (/(y+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            }
            if (/(E+)/.test(fmt)) {
                fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                }
            }
            var str = fmt.lastIndexOf("N");
            if (str != -1) {
                return "";
            }

            return fmt;
        }
        //时间选择
        $('input[name="daterange"]').daterangepicker({
            startDate: moment().startOf('day'),
            endDate: moment(),
            //minDate: '01/01/2012',    //最小时间
            //maxDate: moment(), //最大时间
            dateLimit: {days: 365}, //起止时间的最大间隔
            showDropdowns: true,
            showWeekNumbers: false, //是否显示第几周
            timePicker: false, //是否显示小时和分钟
            timePickerIncrement: 60, //时间的增量，单位为分钟
            timePicker12Hour: false, //是否使用12小时制来显示时间
            ranges: {
                //'最近1小时': [moment().subtract('hours',1), moment()],
                '今日': [moment().startOf('day'), moment()],
                '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
                '最近7日': [moment().subtract('days', 6), moment()],
                '最近30日': [moment().subtract('days', 365), moment()]
            },
            opens: 'right', //日期选择框的弹出位置
            buttonClasses: ['btn btn-default'],
            applyClass: 'btn-small btn-primary blue',
            cancelClass: 'btn-small',
            format: 'YYYY-MM-DD', //控件中from和to 显示的日期格式 YYYY-MM-DD HH:mm:ss
            separator: '~',
            locale: {
                applyLabel: '确定',
                cancelLabel: '取消',
                fromLabel: '起始时间',
                toLabel: '结束时间',
                customRangeLabel: '自定义',
                daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                monthNames: ['一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'],
                firstDay: 1
            }
        }, function (start, end, label) {//格式化日期显示框
            $('.date-rangepicker span').html(start.format('YYYY-MM-DD HH:mm:ss') + ' - ' + end.format('YYYY-MM-DD HH:mm:ss'));
        });

        
        init();
        
        // 确定
        $("#but_submit").click(function(){
        	getPageHtml();
        });
        
        // 确认转单
        $("#coachTransferenceOrder").click(function(){
        	submitCoachTransferenceOrder();
        });
        
        // 
        $("#ul_id li a").click(function(){
        	 $('#ul_id li').removeClass('active');
             $(this).parent().addClass('active');
             $(this).context.innerHTML;
             var type = $(this).context.innerHTML;
             if (type == "已支付" || type == '<a href="#">已支付</a>') {
                 //return "1";
                 $("#orderStatus").val(1);
             }
             if (type == "未支付" || type == '<a href="#">未支付</a>') {
                 //return "5";
            	 $("#orderStatus").val(5);
             }
             if (type == "已结束" || type == '<a href="#">已结束</a>') {
                 //return "2";
                 $("#orderStatus").val(2);
             }
             if (type == "已取消" || type == '<a href="#">已取消</a>') {
            	 //return "3";
                 $("#orderStatus").val(3);
             }
             if (type == "已退款" || type == '<a href="#">已退款</a>') {
                 //return "4";
                 $("#orderStatus").val(4);
             }
             getPageHtml();
        });
        
        
        
    });
	
    // 初始化函数
    function init(){
    	stortList();// 初始化门店列表
    	coachList();// 初始化教练列表
    	getPageHtml();// 加载数据
    }
    // 获取订单数据
    function getPageHtml(){
    	$('.modal-loading').show();
    	// 异步请求数据
    	var url = "get_se_order_list";
    	var param = getParam();
    	
    	$("#td1").empty();
    	$("#orderCount").html("订单合计："+0+"笔");
		$("#orderCost").html("费用合计：￥"+0);
		$("#orderActualAmount").html("实付合计：￥"+0);
    	Ajax(url,param,html);
    	
    }
    
    // 获取参数
    function getParam(){
    	var param = {
        	"orderNumber"	:	$("#orderNumber").val(),
        	"coachId"		:	$("#coach_list").val(),
        	"mobile"		:	$("#mobile").val(),
        	"userId"		: 	$("#userId").val(),
        	"nickName"		:	$("#nickName").val(),
        	"storeId"		:	$("#store_list").val(),
        	"pageNum"		:	$("#pageNum").val(),
        	"type"			:	$("#orderStatus").val(),
        	"orderType"		: 	9
        }
    	return param;
    }
    
    // 设置参数值
    function setParam(params){
    	$("#orderNumber").val(params.orderNumber);
    	$("#coach_list").val(params.coachId);
    	$("#mobile").val(params.mobile);
    	$("#userId").val(params.userId);
    	$("#nickName").val(params.nickName);
    	$("#store_list").val(params.storeId);
    	$("#pageNum").val(params.pageNum);
    }
    
    // 异步请求
    function Ajax(url,param,callBack){
    	$.ajax({
            url: url,//
            data: param,
            type: 'post',
            cache: false,
            dataType: 'json',
            success: function (data) {
            	callBack(data);
            },
            error: function () {
                alert("页面数据加载失败！");
            }
        });
    }
    
    // 加载数据
    function html(jsonData){
    	var datas = jsonData.data;
    	if(jsonData.ret == -1){
    		alert("页面数据加载失败！");
    		return false;
    	}
    	var html = "";
    	var dataJson = datas.SeOrderList;
    	var param = getParam();
    	
    	if(datas.totalCount > 0){
    		for(var i = 0 ; i< dataJson.length ; i++){
    			var data = dataJson[i];
    			
    			var orderStatus = '<button type="button" class="btn btn-default btn-sm" {cancelOrder}>'
    							 +'<span class="glyphicon glyphicon-ban-circle"></span>{type}</button>';
    							 
    			var orderAttorn = '<button type="button" class="btn btn-default btn-sm" {transferTransferlOrder}>'
					 			 +'<span class="glyphicon glyphicon-ban-circle"></span>{type}</button>';
				var cancelOrder = "";
    							 
    			if(param.orderStatus == 1){
    				// 已支付
    				orderStatus = orderStatus.replace('{cancelOrder}','onclick="cancelOrder('+data.order_id+')"');
    				orderStatus = orderStatus.replace("{type}","退款");
    				orderAttorn = orderAttorn.replace("{transferTransferlOrder}",'onclick="transferenceOrderModal('+data.order_id+','+data.order_number+')"');
    				orderAttorn = orderAttorn.replace("{type}","转单");
    			}else if(param.type == 5){
    				// 未支付
    				orderStatus = "";
    				orderAttorn = "";
    			}else if(param.type == 2){
    				// 已结束
    				orderStatus = "";
    				orderAttorn = "";
    			}else if(param.type == 3){
    				// 已取消
    				
    				orderStatus = orderStatus.replace("{type}","退款");
    				orderStatus = orderStatus.replace('{cancelOrder}','onclick="refundOrder('+data.order_id+')"');
    				orderAttorn = "";
    			}else if(param.type == 4){
    				// 已退款
    				button_html = "";
    				orderStatus = "";
    				orderAttorn = "";
    			}else{
    				// 已支付
    				orderStatus = orderStatus.replace('{cancelOrder}','onclick="cancelOrder('+data.order_id+')"');
    				orderStatus = orderStatus.replace("{type}","取消");
    				orderAttorn = orderAttorn.replace("{transferTransferlOrder}",'onclick="transferenceOrderModal('+data.order_id+','+data.order_number+')"');
    				orderAttorn = orderAttorn.replace("{type}","转单");
    			}
    			var amcount =  getPayType(data.pay_type,data.price, data.weixinAmt, data.consumeAmt, data.companyAmt);
    			html = html 
    					+'<tr>'
		    			+'<td>'+(i+1)+'</td>'
		    			+'<td>'+data.trade_id+'</td>'
		    			+'<td id="tk_td">'+new Date(data.created_time).pattern("yyyy-MM-dd HH:mm:ss")+'</td>'
		    			+'<td>'+data.order_number+'</td>'
		    			+'<td>'+(data.coach_name == null ? "" : data.coach_name)+'</td>'
		    			+'<td>'+data.nick_name+'('+data.user_id+')'+'<br>'+data.mobile+'</td>'
		    			+'<td>'+data.level+'</td>'
		    			+'<td>'+data.prime_price+'</td>'
		    			+'<td>'+data.cash_money+'</td>'
		    			+'<td>'+data.person_count+'</td>'
		    			+'<td>'+amcount+'</td>'
		    			+'<td>'+orderStatus+orderAttorn+'</td>'
		    			+'</tr>'
		    			;
    				
    		}
    		$('#td1').append(html);
    		page(datas.pageNum,datas.totalCount);
    		$("#orderCount").html("订单合计："+datas.totalCount+"笔");
    		$("#orderCost").html("费用合计：￥"+datas.totalFee);
    		$("#orderActualAmount").html("实付合计：￥"+datas.totalPayment);
    	}
    	$('.modal-loading').hide();
    }
    
    // 分页
    function page(pageNo,pageCount){
    	new Page({
            parent: $("#tk_page_list"),
            nowPage: pageNo,// 第几页
            pageSize: 20,// 每页条数
            totalCount: pageCount,// 总共有几条
            setting: {
                defaultPage: 7,// 默认显示可点击分页的个数 Math.floor(data.data.pageCount / 10)
                firstPageText: "首页",
                prevPageText: "上一页",
                nextPageText: "下一页",
                lastPageText: "尾页"
            },
            callback: function (nowPage, totalPage) {
                nowPage == "" ? nowPage : pageNum;
                $("#pageNum").val(nowPage);
                getPageHtml();
            }
        });
    }
    
    // 加载门店下拉列表
    function stortList() {
        // 门店
        $.ajax({
            url: 'getStoreList.action',//
            data: "",
            type: 'post',
            cache: false,
            dataType: 'json',
            success: function (data) {
                var dataL = data.data;
                var bool = data.ret;
                var list = '';
                $("#store_list").empty();
                var options = '<option value="0">全部</option>';
                if (bool == 0 || bool == '0') {
                    for (var i = 0; i < dataL.length; i++) {
                        var datas = dataL[i];
                        options = options + '<option value="'
                            + datas.code + '">'
                            + datas.name + '</option>';
                    }

                }
                $("#store_list").append(options);
                $("#store_list").trigger("chosen:updated");
                $("#store_list").trigger("liszt:updated");
                $("#store_list").chosen();
            },
            error: function () {
                alert("页面数据加载失败！");
            }
        });
    }
    
    // 加载教练下拉列表
    function coachList() {
        $.ajax({
            url: 'get_coach_list',
            data: {
            	"isPrivate":1
            },
            type: 'post',
            cache: false,
            dataType: 'json',
            success: function (data) {
                var dataL = data.data;
                var bool = data.ret;
                var list = '';
                $(".coach_list").empty();
                var options = '<option value="0">全部</option>';
                if (bool == 0 || bool == '0') {
                    for (var i = 0; i < dataL.length; i++) {
                        var datas = dataL[i];
                        options = options + '<option value="'
                            + datas.id + '">'
                            + datas.nickName + '</option>';
                    }

                }
                $(".coach_list").append(options);
                $(".coach_list").trigger("chosen:updated");
                $(".coach_list").chosen();

            },
            error: function () {
                alert("页面数据加载失败！");
            }
        });
    }
    
 	// 订单取消函数
    function cancelOrder(orderId) {
    	
    	swal({
            title: "确定取消订单?" + orderId,
            text: "取消订单会退到被动取消里!",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "容我三思！",
            confirmButtonText: "确定!",
        }).then(function () {
            $.ajax({
                url: "updateOrder",              // 请求地址
                data: {
                    "orderId": orderId,
                    "type": 1
                },
                type: 'post',
                cache: false,
                dataType: 'json',
                success: function (data) {
                    // 刷新页面，不刷新整体页面只是刷新table
                    if(data.ret == 0){
                    	swal("保存成功!", "页面即将重新加载,请稍后...", "success");
                        window.setTimeout(function () {
                        	getPageHtml();
                        }, 1000);
                    }else{
                    	swal("取消失败!", "请联系管理员处理", "error");
                    }
                    
                },
                error: function () {
                    swal("取消失败!", "请联系管理员处理", "error");
                }
            });

        }, function () {
		});
    }
    
    // 退款函数
    function refundOrder(orderId){
    	swal({
            title: "确定退款" + orderId,
            text: "退款之后金额直接打入对方账户!",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "容我三思！",
            confirmButtonText: "确定!",
        }).then(function () {
            $.ajax({
                url: "createdRefun.action",              // 请求地址
                data: {
                    "orderId": orderId,
                    "biaoshi": 1
                },
                type: 'post',
                cache: false,
                dataType: 'json',
                success: function (data) {
                	if(data.ret == 0){
                		swal("退款成功!", "您已退款成功,金额已打入对方账户", "success");
                        window.setTimeout(function () {
                        	getPageHtml();
                        }, 1000);
                	}else{
                		swal("退款失败!", data.msg, "error");
                	}
                    
                },
                error: function () {
                    swal("退款失败!", "系统运行异常，请联系管理员处理", "error");
                }
            });

        }, function () {
    	});
    }
    
    // 转单模态框
    function transferenceOrderModal(orderId,orderNumber){
    	$("#myModalLabel").html("是否确认将订单编号："+orderNumber+"转给别的教练");
    	$("#coachOrderId").val(orderId);
    	$('#coach_myModal').modal('show');
    }
    
    // 确认转单
    function submitCoachTransferenceOrder(){
    	var url = "transference_order";
    	var param = {
    			"orderId": $("#coachOrderId").val(),
    			"coachId": $("#coach_list_order").val(),
    			"type"	 : 1
    	}
    	$('#coach_myModal').modal('hide');
    	if($("#coach_list_order").val() != 0){
    		Ajax(url,param,transferenceOrder);
    	}else{
    		swal("转单失败!", "请指定教练", "error");
    	}
    	
    }
    
    // 转单
    function transferenceOrder(data){
    	debugger;
    	if(data.ret == 0){
        	swal("转单成功!", "页面即将重新加载,请稍后...", "success");
            window.setTimeout(function () {
            	getPageHtml();
            }, 1000);
        }else{
        	swal("转单失败!", "请联系管理员处理", "error");
        }
    	
    }
    
    function getPayType(payType, amcount, wechatAccount, personAccount, companyAccount){
    	var patTypeMsg = "";
    	if(payType == 1){
    		patTypeMsg = amcount+"(微)";
    	}else if(payType == 2){
    		patTypeMsg = amcount+"(储)";
    	}else if(payType == 3){
    		patTypeMsg = amcount+"(企)";
    	}else if(payType == 4){
    		patTypeMsg = amcount+"(微_"+wechatAccount+"/储_"+personAccount+")";
    	}else if(payType == 2){
    		patTypeMsg = amcount+"(微_"+wechatAccount+"/企_"+companyAccount+")";
    	}else{
    		patTypeMsg = amcount+"(微)";
    	}
    	return patTypeMsg;
    }
</script>

</@body.page>
</html>